#include "stdafx.h"

#include "ResourceGroup.h"

namespace GMotor
{
	ResourceGroup::ResourceGroup(std::string name,StdTools::LogManager * logManager)
	{
		this->initialized = false;

		this->name = name;
		this->mLogManager = logManager;

		this->thread = new StdTools::Threads::Thread(this);

		this->mLogManager->systemLogMessage("Creado grupo " + name + ".");
	}

	ResourceGroup::~ResourceGroup()
	{
		StdTools::Threads::Thread::join(this->thread);
		this->mLogManager->systemLogMessage("Eliminando grupo " + this->name + "...");
		std::list<Resource *>::iterator it;
		for (it = this->lstResource.begin(); it != this->lstResource.end(); it++)
		{
			this->mLogManager->systemLogMessage("Eliminado recurso " + (*it)->getName() + " del grupo " + this->name + ".");
			delete *it;
		}
		this->mLogManager->systemLogMessage("Grupo " + this->name + " eliminado.");
	}

	std::string ResourceGroup::getName()
	{
		return this->name;
	}

	Resource * ResourceGroup::getResource(std::string name)
	{
		Resource * resource = NULL;
		std::list<Resource *>::iterator it;
		for (it = this->lstResource.begin(); it != this->lstResource.end(); it++)
			if ((*it)->getName()==name)
			{
				resource = *it;
				resource->initialize();
			}
		return resource; 
	}

	void ResourceGroup::addResource(Resource * resource)
	{
		this->lstResource.push_back(resource);
		this->mLogManager->systemLogMessage("Anadido recurso " + resource->getName() + " al grupo " + this->name + ".");
	}

	bool ResourceGroup::deleteResource(std::string name)
	{
		bool encontrado = false;
		std::list<Resource *>::iterator it;
		for (it = this->lstResource.begin(); !encontrado && it != this->lstResource.end(); it++)
			if ((*it)->getName()==name)
				encontrado = true;
		if (encontrado)
		{	
			it--;
			this->mLogManager->systemLogMessage("Eliminado recurso " + (*it)->getName() + " del grupo " + this->name + ".");
			delete *it;
			this->lstResource.erase(it);
		}
		return encontrado;
	}

	void ResourceGroup::initialize()
	{
		this->mutex.lock();
		if (!this->initialized)
			this->thread->start();
	}

	void ResourceGroup::Run()
	{
		this->mLogManager->systemLogMessage("Inicializando grupo " + this->name + "...");
		std::list<Resource *>::iterator it;
		for (it = this->lstResource.begin(); it != this->lstResource.end(); it++)
			(*it)->initialize();
		this->initialized = true;
		this->mLogManager->systemLogMessage("Grupo " + this->name + " inicializado.");
		this->mutex.unlock();
	}
}